package com.faiz.ugla.griplog;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class FakeCall extends Activity implements OnClickListener {

	private Button answerButton;
	private TextView participantLabel;
	private TextView taskLabel;
	private Ringtone rTone;
	private Uri notification;
	private Intent fakeCallInitIntent;
	private Intent fakeCallAnswerIntent;
	private Bundle bundle;
	private String currentParticipant;
	private int task;
	private SharedPreferences appSettings;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_fake_call);

		PreferenceManager.setDefaultValues(this, R.xml.prefs, false);
		appSettings = PreferenceManager.getDefaultSharedPreferences(this);

		answerButton = (Button) findViewById(R.id.answer_button);
		answerButton.setOnClickListener(this);	

		participantLabel = (TextView) findViewById(R.id.fc_participant_label);
		taskLabel = (TextView) findViewById(R.id.fc_task_label);

		//Create intents
		fakeCallInitIntent = new Intent();
		fakeCallInitIntent.setAction(LoggingService.FAKE_CALL_INIT_ACTION);

		fakeCallAnswerIntent = new Intent();
		fakeCallAnswerIntent.setAction(LoggingService.FAKE_CALL_ANSWER_ACTION);

		//Play ringtone
		notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
		rTone = RingtoneManager.getRingtone(getApplicationContext(), notification);
		rTone.play();
	}

	@Override
	protected void onResume() {
		super.onResume();

		//Task number
		bundle = this.getIntent().getExtras();
		task = Integer.parseInt(bundle.getString("task"));

		currentParticipant = appSettings.getString("CONFIG_PARTICIPANT_INFO_KEY", "1");

		participantLabel.setText("Participant# " + currentParticipant);
		taskLabel.setText("Task# " + String.valueOf(task));

		//Send broadcast to LoggingService
		fakeCallInitIntent.putExtra("Initiated", true);
		fakeCallInitIntent.putExtra("Task", task);
		sendBroadcast(fakeCallInitIntent);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	public void onClick(View v) {

		switch(v.getId()) {
		case R.id.answer_button:

			//Answer call intent
			fakeCallAnswerIntent.putExtra("Answered", true);
			sendBroadcast(fakeCallAnswerIntent);

			//Stop ringtone
			rTone.stop();
			finish();
			break;
		}
	}
}
